/**
 * @Author 韦建韩
 * @Date 2022/5/9
 */
package com.example.devops.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.devops.Conntext.ResponseContext;
import com.example.devops.dao.UserMapper;
import com.example.devops.entity.common.Result;
import com.example.devops.entity.pojo.User;
import com.example.devops.exception.ValidationException;
import com.example.devops.util.JwtUtil;
import com.example.devops.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Service
public class UserService {
    @Autowired(required = false)
    UserMapper userMapper;
    @Autowired
    RedisUtil redisUtil;
    public Result save(User u){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", u.getAccount());
        User user = userMapper.selectOne(queryWrapper);
        if(Objects.nonNull(user)){
            throw new ValidationException("该账号已被注册");
        }
        userMapper.insert(u);
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper.eq("account", u.getAccount());
        User user2 = userMapper.selectOne(queryWrapper);

        return Result.doCreate(user2);
    }

    public Result login(User user){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", user.getAccount());
        queryWrapper.eq("password", user.getPassword());
        User userRes = userMapper.selectOne(queryWrapper);
        if(Objects.isNull(userRes)){
            throw new ValidationException("账号或密码错误");
        }
        HttpServletResponse response = ResponseContext.getM();

        String tokenString = JwtUtil.getTokenString(userRes);
        redisUtil.setValue(userRes.getAccount(), "user");
        Cookie cookie = new Cookie("token", tokenString);
        cookie.setHttpOnly(false);
        cookie.setMaxAge(60*60);
        cookie.setPath("/");
        response.addCookie(cookie);
        return Result.doCreate(userRes);
    }

    public Result getAllUse(){
        List<User> users = userMapper.selectList(null);
        return Result.doCreate(users);
    }
}
